package client;
import java.io.*;
import java.util.Observable;
import java.util.Observer;

import model.CommandProcessor;


/**
 * @author Danilov
 *
 */
public class ConsoleView implements Runnable, Observer{

	private final CommandProcessor cmdProcessor;
	
	private String userName = "User";

	public ConsoleView(CommandProcessor proc){
		cmdProcessor = proc;
	}

	/**
	 * Returns user input, and makes sure everything is nice and clean
	 * @return
	 * @throws IOException
	 * @throws InterruptedException
	 */
	private String GetInput() throws IOException, InterruptedException{
		// For handling user input
		BufferedInputStream in = new BufferedInputStream(System.in);
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		int data = 0;
		do {
			data = in.read();
			bout.write(data);
		} while(data != 13);

		String result = bout.toString();
		if (result.charAt(result.length() - 1) == '\r'){
			result = result.substring(0, result.length() - 1);
		}

		return result;
	}

	public final String helpString = "PrimeTerminal v.1.0.0.0. Available commands are:%n help%n post %%positivenumber%%%n ip %%ipaddress:port%%%n exit%n%s> ";
	
	@Override public void run() {
		System.out.printf(helpString, userName);
		while (true){
			try {
				String cmd = GetInput();
				String answer = cmdProcessor.postInput(cmd);
				System.out.printf("System> %n%s%n%s> ", answer, userName);
				
				// Give OS time to output the response
				Thread.sleep(300);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	
	/**
	 * Whenever model is ready to report data you simple output them immediately
	 */
	@Override public void update(Observable o, Object arg) {
		if (arg instanceof String) {
			System.out.printf("%nServer> %s%n%s>", arg, userName);
		} else {
			System.out.println("Server> bargargahgghh.....");
		}
	}
}
